package com.kaiwukj.android.ufamily.mvp.helper;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;

public class AccountStore {

    private static final String KAccount = "k_account";
    private static final String KUserResult = "k_user";

    private UserResult userResult;
    private static AccountStore instance;

    private AccountStore() {
    }

    public static void init() {
        if (instance == null) {
            instance = new AccountStore();
        }
    }


    public synchronized static UserResult getUserResult() {
        if (instance == null) return new UserResult();
        if (instance.userResult == null)
            instance.userResult = GsonUtils.fromJson(SPUtils.getInstance(KAccount).getString(KUserResult), UserResult.class);
        return instance.userResult;
    }

    public static void login(UserResult userResult) {
        SPUtils.getInstance(KAccount).put(KUserResult, GsonUtils.toJson(userResult));
        instance.userResult = userResult;
    }

    public static void updateUserCache(UserResult result) {
        if (result == null) return;
        //instance.userResult = result;
        login(result);
    }

    public static void updateCommunity(int communityId, String communityName) {
        UserResult result = getUserResult();
        result.setLastCommunityId(communityId);
        result.setLastCommunityName(communityName);
        updateUserCache(result);
    }

    public static void logout() {
        instance.userResult = null;
        SPUtils.getInstance(KAccount).clear();
        TokenStore.clear();
    }

    public static boolean isLogin() {
        return getUserResult() != null && getUserResult().getId() != null && getUserResult().getId() > 0;
    }


}
